package xyz.zq.validation.util;

import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * http 请求工具类
 */
public class HttpUtil {

    /**
     * 获取Get请求参数
     *
     * @param request HttpServletRequest
     * @return Map
     */
    public static Map<String, Object> getRequestParameterMap(HttpServletRequest request) {

        Enumeration<String> parameterNames = request.getParameterNames();

        Map<String, Object> map = new HashMap<>();

        while (parameterNames.hasMoreElements()) {

            String nextElement = parameterNames.nextElement();

            String parameter = request.getParameter(nextElement);

            map.put(nextElement, parameter);
        }

        return map;
    }

    /**
     * 获取Get请求参数
     *
     * @return Map
     */
    public static Map<String, Object> getRequestParameterMap() {
        return getRequestParameterMap(getHttpServletRequest());
    }

    public static ServletRequestAttributes getServletRequestAttributes() {

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();

        Assert.notNull(servletRequestAttributes, "HttpServletRequest 不能为空");

        return servletRequestAttributes;
    }

    public static HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    public static HttpServletRequest getHttpServletRequest(ServletRequestAttributes servletRequestAttributes) {
        return servletRequestAttributes.getRequest();
    }

    public static HttpServletResponse getHttpServletResponse() {
        return getServletRequestAttributes().getResponse();
    }

    public static HttpServletResponse getHttpServletResponse(ServletRequestAttributes servletRequestAttributes) {
        return servletRequestAttributes.getResponse();
    }

    public static ServletWebRequest getServletWebRequest() {

        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();

        return new ServletWebRequest(
                getHttpServletRequest(servletRequestAttributes),
                getHttpServletResponse(servletRequestAttributes));
    }


}
